<template>
  <div>
    <div class="boxWrapper tabbox">
      <el-tabs v-model="currentName">
        <el-tab-pane label="图片数字化" name="1">
          <span slot="label"><i class="iconfont">&#xe61f;</i> 图片数字化</span>
        </el-tab-pane>
        <el-tab-pane label="变位图配置" name="2">
          <span slot="label"><i class="iconfont">&#xe752;</i> 变位图配置</span>
        </el-tab-pane>
      </el-tabs>
    </div>
    
    <div class="imageSetting" v-show="currentName == 1">
        <BoxWithTitle class="left-wrapper" title="目录" icon="&#xe6f2;" isOther>
            <template #other>
                <el-select v-model="stationId" placeholder="请选择" size="small" class="form-item" @change="onGetMenuList()" style="width:160px">
                    <el-option v-for="item in stationList" :key="item.id" :label="item.stationName" :value="item.id"></el-option>
                </el-select>
            </template>
            <div class="menu-tree">
                <el-button v-if="menuList.length == 0" type="primary" size="small" style="margin: 80px 0 0 120px;" @click="handleAddMenu({node:{}},0,1)">新增目录</el-button>
                <treeMenu :treeData="menuList" name="lable" ref="treeMenu" nodeKey="id" expandALL @menuLeftClick="handleChangeMenu" isRightMenu
                @addMenuItem="handleAddMenu"
                @delMenuItem="handleDelTreeMenu"
                @editMenuItem="handleAddMenu"/>
            </div>
        </BoxWithTitle>

        <!-- 中间图像查看器 -->
        <ImageViewer
            :imageUrl="imageUrl"
            :graphTreeID="graphTreeID"
            :selectDrawType="selectDrawType"
            :allElementPoint="allElementPoint"
            :allElementText="allElementText"
            :externalScaleLine="scaleForm"
            @upload-bg="uploadFileBg"
            @point-click="handlePointClick"
            @text-click="handleTextClick"
            @scale-drawn="handleScaleDrawn"
            @image-loaded="handleImageLoaded"
            isDigitalization
        />

        <ToolPanel
            :selectDrawType="selectDrawType"
            :allElementPoint="allElementPoint"
            :allElementText="allElementText"
            @change-draw-type="handleChangeDrawType"
            @edit-point="handleEditPoint"
            @del-point="handleDelPoint"
            @edit-text="handleEditText"
            @del-text="handleDelText"
        />
    </div>


    <el-dialog title="菜单配置" :visible.sync="dialogPointMenuVisible" width="600px" v-dialogDrag class="menu-config-dialog">
        <div class="dialog-content">
        <el-form :model="pointMenuForm" label-width="100px" ref="form" label-position="left">
          <el-form-item label="目录名称" prop="treeName">
            <el-input 
              v-model="pointMenuForm.treeName" 
              placeholder="请输入目录名称"
              prefix-icon="el-icon-tickets"
              clearable>
            </el-input>
          </el-form-item> 
          <el-form-item label="底图路径" class="upload-item">
            <el-upload
              class="upload-area"
              action="#"
              :http-request="uploadFile"
              :show-file-list="false"
              >
              <div class="upload-content">
                <i class="el-icon-upload" v-if="!pointMenuForm.imgUrl"></i>
                <div class="upload-text">
                  <div class="file-name">{{ pointMenuForm.imgUrl || '点击上传底图' }}</div>
                  <el-button size="small" type="" v-if="pointMenuForm.imgUrl">
                    更换图片
                  </el-button>
                </div>
              </div>
            </el-upload>
            <div class="upload-tips">支持JPG、PNG格式，大小不超过2MB</div>
          </el-form-item>
        </el-form>
      </div>
      
      <div class="dialog-footer">
        <el-button @click="dialogPointMenuVisible = false" class="cancel-btn" icon="el-icon-close" round size="medium">取消</el-button>
        <el-button 
          type="primary" 
          @click="handleSavePointMenu" 
          icon="el-icon-check"
          class="confirm-btn" round size="medium" :disabled="!pointMenuForm.treeName">
          保存配置
        </el-button>
      </div>
    </el-dialog>

    <!-- 弹窗组件 -->
    <svgPointDialog
        :visible="dialogPointPosition"
        :pointForm="pointForm"
        :stationId="stationId"
        @update:pointForm="pointForm = $event"
        @save="handleSavePointPositon"
        @cancel="handleCancelPointPositon"
    />

    <svgTextDialog
      :visible="dialogTextPosition"
      :textForm="textForm"
      :stationId="stationId"
      :dynamicTags="dynamicTags"
      @save="handleSaveTextPositon"
      @cancel="handleCancelTextPositon"
    />

    <svgScaleDialog
      :visible="dialogScaleVisible"
      :scaleForm="scaleForm"
      @save="handleSaveScaleForm"
      @cancel="handleCancelScaleForm"
    />

    <imageSetPage v-if="currentName == 2"/>

  </div>
</template>

<script>
import ImageViewer from '@/components/page/setting/imageViewer.vue'
import svgPointDialog from '@/components/page/setting/svgPointDialog.vue'
import ToolPanel from '@/components/page/setting/toolPanel.vue'
import svgTextDialog from '@/components/page/setting/svgTextDialog.vue'
import svgScaleDialog from '@/components/page/setting/svgScaleDialog.vue'
import BoxWithTitle from '@/components/base/BoxWithTitle.vue'
import treeMenu from '@/components/base/treeMenu.vue'
import bus from '@/utils/eventBus.js';
import imageSetPage from '@/components/page/setting/imageSetPage.vue'
import { 
  GetStationByCompanyID, GetBWTBaseTree, getListByGraphTreeID, 
GraphPointAdd, GraphPointEdit, GraphPointDel, 
  GraphConfigEdit, GraphConfigAdd, getConfigsByTreeID, 
  GraphScaleEdit, GraphScaleAdd,getConfigByID, GraphConfigDel,
  GraphTreeAdd, GraphTreeDel, GraphTreetEdit,getGraphScale 
} from '@/api/https'

export default {
  name: 'ImageSetting',
  components: { BoxWithTitle, treeMenu, ImageViewer, ToolPanel, svgPointDialog,svgTextDialog,svgScaleDialog,imageSetPage
  },
  data() {
    return {
      currentName: '1',
      menuList: [],
      stationList: [],
      stationId: '',
      imageUrl: '',
      graphTreeID: null,
      selectDrawType: '',
      allElementPoint: [],
      allElementText: [],
      svgW: 0,
      svgH: 0,
      upImageUrl:'',
      dialogPointPosition: false,
      dialogTextPosition: false,
      tagSettingDialog: false,
      dialogPointMenuVisible: false,
      dialogScaleVisible: false,
      dialogUnitVisble: false,
      pointForm: {},
      textForm: {},
      pointMenuForm: {},
      scaleForm: {},
      unitList: [],
      editPoint: false,
      editTextTag: false,
      editTagIndex: '',
      treeDataEdit: false,
      treeNodeLevel: '',
      dynamicTags:[],
      editText:false
    }
  },
    mounted(){
        bus.$emit('showBasin', false);
        this.onGetStationList()
    },
    activated(){
        bus.$emit('showBasin', false);
    },
    beforeDestroy(){
        
    },
  methods: {
    onGetStationList () {
        GetStationByCompanyID(0).then(res=>{
            if (res.isSuccess) {
                this.stationList = res.data || []
                this.stationId = res.data[3]?.id || ''
                this.onGetMenuList()
            } else {
                this.stationList = []
                this.stationId = ''
            }
        })            
    },

    onGetMenuList(id) {
        GetBWTBaseTree({StationID: this.stationId}).then(res=>{
            if (res.isSuccess) {
                this.menuList = res.data
                if (this.menuList.length > 0) {
                    if (id) {
                        this.$nextTick(() => {
                            this.graphTreeID = id
                            this.$refs.treeMenu.$refs.tree.setCurrentKey(id)
                            this.handleChangeMenu()
                        })
                    } else {
                        this.$nextTick(() => {
                            this.graphTreeID = res.data[0]?.id || null
                            this.$refs.treeMenu.$refs.tree.setCurrentKey(res.data[0].id)
                            if (res.data[0]?.node?.imgUrl) {
                            this.imageUrl = res.data[0].node.imgUrl
                            }else{
                                this.imageUrl = ''
                            }
                        })
                    }
                }
            } else {
                    this.menuList = []
            }
        })
    },

    async onListByGraphTreeID() { 
      if (!this.graphTreeID) return
      try {
        // 获取测点
        const pointRes = await getListByGraphTreeID({
          GraphTreeID: this.graphTreeID,
          w: this.svgW,
          h: this.svgH
        })
        this.allElementPoint = pointRes.isSuccess ? pointRes.data || [] : []

        // 获取文字
        const textRes = await getConfigsByTreeID({
          treeID: this.graphTreeID,
          width: this.svgW,
          height: this.svgH,
          dt: '',
          length: ''
        })
        this.allElementText = textRes.isSuccess ? textRes.data || [] : []
      } catch (error) {
        console.error('获取图形数据失败:', error)
      }
    },

    async handleChangeMenu(data) {
        this.selectDrawType = 0
        this.dialogScaleVisible = false
      const menuData = data || this.$refs.treeMenu.$refs.tree.getCurrentNode().node
      if (menuData) {
        this.pointMenuForm = { ...menuData }
        this.graphTreeID = menuData.id
        this.imageUrl = menuData.imgUrl || ''
        this.onListByGraphTreeID();
      }
    },


    // 菜单相关操作
    handleAddMenu(data,isEdit,treeNodeLevel){  
        this.treeDataEdit = isEdit
        this.treeNodeLevel = treeNodeLevel || ''
        if(isEdit){
            const _editData = Object.assign({},data.node)
            if(_editData.imgUrl && _editData.imgUrl != ''){
                const imageName = _editData.imgUrl.substring(_editData.imgUrl.lastIndexOf("/")+1)
                _editData.imgUrl = imageName
            }
            this.pointMenuForm = {..._editData}
        }else{
            this.pointMenuForm = {
                id: 0,
                treeID:0,
                stationID: this.stationId,
                treeName:'',
                upTreeID: treeNodeLevel == 1 ? data.node.upTreeID || 0 : data.node.treeID || 0,
                isBottom:0,
                imgUrl: '',
                indexId: 0,
                categroy: 7
            }
        }
        this.dialogPointMenuVisible = true
    },
    handleDelTreeMenu(data){
        this.$confirm(`确认删除名称为 ${data.node.treeName} 的节点？`,'提示',{
            type:'warning'
        }).then(() => {
            GraphTreeDel(data.id).then(res=>{
                if(res.isSuccess){
                    if(this.graphTreeID == data.id){
                        this.pointMenuForm = {}
                        this.onGetMenuList()
                    }else{
                        this.pointMenuForm = {}
                        this.onGetMenuList(this.graphTreeID)
                    }
                    
                }else{
                    this.$message.error(res.errorMessage)
                }
            })
        }).catch(() => {});  
    },
    uploadFile(file) {
        this.pointMenuForm.imgUrl = file.file.name
        let reader = new FileReader()
        reader.readAsDataURL(file.file)
        reader.onload = () => {
            this.pointMenuForm.imgDate = reader.result
            this.pointMenuForm.imgUrl = file.file.name
        }
    },
    handleSavePointMenu(){
        if(this.treeDataEdit){
            GraphTreetEdit(this.pointMenuForm).then(res=>{
                if(res.isSuccess){
                    this.onGetMenuList(this.pointMenuForm.id)
                    this.dialogPointMenuVisible =false
                    this.pointMenuForm = {}
                }else{
                    this.$message.error(res.errorMessage)
                }
            })
        }else{
            const data = {
                id: this.pointMenuForm.id || 0,
                treeID: this.pointMenuForm.treeID || 0,
                stationID: this.stationId,
                treeName:this.pointMenuForm.treeName,
                upTreeID: this.pointMenuForm.upTreeID || 0,
                isBottom: this.pointMenuForm.isBottom || 0,
                imgUrl: this.pointMenuForm.imgUrl || '',
                indexId: this.pointMenuForm.indexId || 0, 
                categroy: 7,
                imgDate:this.pointMenuForm.imgDate || ''
            }
            GraphTreeAdd(data).then(res=>{
                if(res.isSuccess){ 
                    this.onGetMenuList(res.data)
                    this.dialogPointMenuVisible =false
                }else{
                    this.$message.error(res.errorMessage)
                }
            })
        }
    },

    // 配置工具
    handleChangeDrawType(type) {
      if (!this.imageUrl) {
        this.$message.error('请先选择底图！')
        return
      }
      this.selectDrawType = type
      if (type === 2) {
        this.handleScaleToolClick()
      }
    },

    // 测点定位
    handleEditPoint(item) {
      this.pointForm = { ...item }
      this.editPoint = true
      this.dialogPointPosition = true
    },
    handlePointClick(point) {
      this.pointForm = {
        pointName: '',
        startX: point.x,
        startY: point.y,
        pointSize: 4,
        color: '#f00',
        ifBorder: 0,
        borderSize: 1,
        borderColor: '#000000',
        fontColor: '',
        fontFamily: '',
        fontSize: 0,
        h: this.svgH,
        w: this.svgW,
        id: 0,
        lineType: 1,
        treeID: this.graphTreeID,
      }
      this.editPoint = false
      this.dialogPointPosition = true
    },
    async handleSavePointPositon(pointData) {
      try {
        let res
        if (this.editPoint) {
          res = await GraphPointEdit(pointData)
        } else {
          res = await GraphPointAdd(pointData)
        }
        
        if (res.isSuccess) {
          this.dialogPointPosition = false
          this.onListByGraphTreeID()
          this.$message.success('保存成功')
        } else {
          this.$message.error(res.errorMessage)
        }
      } catch (error) {
        console.error('保存测点失败:', error)
        this.$message.error('保存失败')
      }
    },
    handleCancelPointPositon() {
      this.dialogPointPosition = false
      this.pointForm = {}
    },
    handleDelPoint(data){
        this.$confirm(`确认要删除名称为 ${data.pointName} 测点？`, '提示', {
            type: 'warning'
            }).then(() => {
                GraphPointDel(data.id).then(res=>{
                    if(res.isSuccess){
                        this.pointToolShow = false
                        this.onListByGraphTreeID()
                    }else{
                        this.$message.error(res.errorMessage)
                    }
                })
            }).catch(() => {        
        });
    },
    // 添加文字
    handleSaveTextPositon(data,previewText) {
        if (this.editText) {
            GraphConfigEdit({
                ID: data.ID,
                TreeID: this.graphTreeID,
                cont: previewText,
                fontSize: data.fontSize,
                x:data.x,
                y: data.y,
                width: 0,
                imageWidth: this.svgW,
                imageHeight: this.svgH
            }).then(res=>{
                if(res.isSuccess){
                    this.handleCancelTextPositon()
                    this.onListByGraphTreeID()
                }else{
                    this.$message.error(res.errorMessage)
                }
            })
        } else {
            GraphConfigAdd({
                ID: 0,
                TreeID: this.graphTreeID,
                cont: previewText,
                fontSize: data.fontSize,
                x: data.x,
                y: data.y,
                width: 0,
                imageWidth: this.svgW,
                imageHeight: this.svgH
           }).then(res=>{
                if(res.isSuccess){
                    this.handleCancelTextPositon()
                    this.onListByGraphTreeID()
                }else{
                    this.$message.error(res.errorMessage)
                }
            })
        }
    },
    handleCancelTextPositon(){
        this.dialogTextPosition = false
        this.textForm = {}
        this.editTextTag = false
        this.dynamicTags = []
        this.editText = false
    },
    handleEditText(data){
        this.editText = true
        getConfigByID({
            id:data.ID,
            width:this.svgW,
            height:this.svgH
        }).then(res=>{
            if(res.isSuccess){
                this.textForm = {...res.data}
                this.editTextTag = true
                this.dialogTextPosition = true
                this.dynamicTags = res.data.contItems
            }else{
                this.$message.error(res.errorMessage)
            }
        })
    },
    handleDelText(data){
        this.$confirm('确认要删除该条记录？', '提示', {
            type: 'warning'
            }).then(() => {
                GraphConfigDel({
                    ID:data.ID
                }).then(res=>{
                    if(res.isSuccess){
                        this.onListByGraphTreeID()
                    }else{
                        this.$message.error(res.message)
                    }
                })
            }).catch(() => {        
        });
    },
    handleTextClick(position) {
      this.textForm = {
        x: position.x,
        y: position.y,
        fontSize: 14
      }
      this.editTextTag = false
      this.dialogTextPosition = true
    },

    // 绘制底图
    handleImageLoaded(size) {
      this.svgW = size.width
      this.svgH = size.height
      this.onListByGraphTreeID()
    },

    uploadFileBg (file) {
        const _data = {...this.pointMenuForm}
        _data.imgUrl = file.file.name
        let reader = new FileReader()
        reader.readAsDataURL(file.file)
        reader.onload = () => {
            _data.imgDate = reader.result
            GraphTreetEdit(_data).then(res=>{
                if(res.isSuccess){
                    this.onGetMenuList(this.pointMenuForm.id)
                }else{
                    this.$message.error(res.errorMessage)
                }
            })
        }
    },
    
    //  比例尺
    async handleScaleToolClick() {
      try {
        const res = await getGraphScale({
          TreeID: this.graphTreeID
        });
        
        if (res.isSuccess) {
          this.scaleForm = {...this.scaleForm, ...res.data };
          this.dialogScaleVisible = true;
        } else {
          this.$message.error(res.errorMessage);
        }
      } catch (error) {
        
      }
    },
    handleSaveScaleForm(data){
        if (data.id) {
        GraphScaleEdit(data).then(res => {
          if (res.isSuccess) {
            this.$message.success('修改成功！');
            // 保存成功后更新imageViewer中的比例尺显示
            this.$nextTick(() => {
              this.$refs.imageViewer?.displayScaleLine?.({
                x1: data.x1,
                y1: data.y1,
                x2: data.x2,
                y2: data.y2
              });
            });
            this.handleCancelScaleForm();
          } else {
            this.$message.error(res.errorMessage);
          }
        });
      } else {
        const _d = {...data};
        _d.treeID = this.graphTreeID;
        GraphScaleAdd(_d).then(res => {
          if (res.isSuccess) {
            this.$message.success('设置成功！');
            // 保存成功后更新imageViewer中的比例尺显示
            this.$nextTick(() => {
              this.$refs.imageViewer?.displayScaleLine?.({
                x1: data.x1,
                y1: data.y1,
                x2: data.x2,
                y2: data.y2
              });
            });
            this.handleCancelScaleForm();
          } else {
            this.$message.error(res.errorMessage);
          }
        });
      }
    },
    handleCancelScaleForm(){
        this.dialogScaleVisible = false
        this.selectDrawType = 0
        this.scaleForm = {}
    },

    handleScaleDrawn(scaleLine) {
        // 更新比例尺表单数据，包含当前的calcWay
        this.scaleForm = {
            ...this.scaleForm,
            x1: scaleLine.x1,
            y1: scaleLine.y1,
            x2: scaleLine.x2,
            y2: scaleLine.y2,
            calcWay: this.scaleForm.calcWay || 3 // 保持原有的计算方式
        };
        
        // 如果比例尺对话框是打开的，更新显示
        if (this.dialogScaleVisible) {
            this.$nextTick(() => {
            // 触发比例尺对话框的更新
            this.$refs.scaleDialog?.updateScaleData?.(this.scaleForm);
            });
        }
    },    

    }

  }

</script>

<style scoped lang="scss">
.imageSetting {
  display: flex;
  flex-direction: row;
  justify-content: start;
  margin-top: 10px;
  gap: 5px;
  height: calc(100vh - 180px);
  
}

.boxWrapper.tabbox {
  margin-bottom: 10px;
}

.menu-tree{
    height: calc(100vh - 240px);
    width:320px;
    overflow: auto;
}

.dialog-content {
  padding: 10px 0;
}

::v-deep .advanced-menu-dialog .el-form-item {
  margin-bottom: 22px;
}


::v-deep .advanced-menu-dialog .el-input__inner {
  border-radius: 8px;
  transition: all 0.3s ease;
  padding: 12px 15px;
  height: 44px;
  border: 1px solid #e2e8f0;
  color: #2d3748;
  font-family: inherit;
}

::v-deep .advanced-menu-dialog .el-input__inner:focus {
  border-color: #4776E6;
  box-shadow: 0 0 0 2px rgba(71, 118, 230, 0.2);
}

/* 上传区域样式 */
.upload-item ::v-deep .el-form-item__content {
  line-height: 1.5;
}

.upload-area {
  border: 2px dashed #cbd5e0;
  border-radius: 10px;
  padding: 20px;
  text-align: center;
  transition: all 0.3s ease;
  background: #f8fafc;
  cursor: pointer;
}

.upload-area:hover {
  border-color: #4776E6;
  background: #f0f5ff;
}

.upload-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 12px;
}

.upload-content .el-icon-upload {
  font-size: 40px;
  color: #4776E6;
}

.upload-image-preview {
  width: 80px;
  height: 80px;
  object-fit: cover;
  border-radius: 6px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

.upload-text {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
}

.file-name {
  color: #4a5568;
  font-weight: 500;
  max-width: 200px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.upload-tips {
  font-size: 12px;
  color: #718096;
  margin-top: 8px;
  text-align: center;
}

</style>